package com.zhj.agent.interceptor.resttemplate.sync;

import com.zhj.agent.common.ConstName;
import com.zhj.agent.core.RuntimeContextManager;
import com.zhj.agent.support.InstanceMethodsAroundInterceptor;

import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.List;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class RestResponseInterceptor implements InstanceMethodsAroundInterceptor {

    /**
     * Before method
     *
     * @param objInst        obj inst
     * @param method         method
     * @param allArguments   all arguments
     * @param argumentsTypes arguments types
     * @throws Throwable throwable
     * @since 1.0.0
     */
    @Override
    public void beforeMethod(Object objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes) throws Throwable {

    }

    /**
     * After method
     *
     * @param objInst        obj inst
     * @param method         method
     * @param allArguments   all arguments
     * @param argumentsTypes arguments types
     * @param result         result
     * @return the object
     * @throws Throwable throwable
     * @since 1.0.0
     */
    @Override
    public Object afterMethod(Object objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Object result) throws Throwable {
        ClientHttpResponse clientHttpResponse = (ClientHttpResponse) allArguments[1];
        List<String> traceList = clientHttpResponse.getHeaders().get(ConstName.HEAD_KEY);
        if (!CollectionUtils.isEmpty(traceList)) {
            RuntimeContextManager.remove();
            traceList.forEach(trace -> {
                RuntimeContextManager.add(RuntimeContextManager.CarrierItem.item(trace, trace));
            });
        }
        return result;
    }

    /**
     * Handle method exception
     *
     * @param objInst        obj inst
     * @param method         method
     * @param allArguments   all arguments
     * @param argumentsTypes arguments types
     * @param t              t
     * @since 1.0.0
     */
    @Override
    public void handleMethodException(Object objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) {
        RuntimeContextManager.printTraceLog();
    }
}
